package com.zbkj.client.controller;

import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.client.service.KnowledgeService;
import com.zbkj.common.model.assets.Knowledge;
import com.zbkj.common.request.client.KnowledgeAddRequest;
import com.zbkj.common.request.client.BatchDeleteRequest;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.result.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/client/assets")
@Api(tags = "知识库管理")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @ApiOperation(value = "添加知识库素材")
    @PostMapping(value = "/addKnowledge", consumes = "multipart/form-data")
    public CommonResult<Map<String, Object>> addKnowledge(
            @ModelAttribute KnowledgeAddRequest request,
            HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("token");
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        Integer parentId = request.getParentId();
        if (parentId != null && parentId != 0) {
            Knowledge parent = knowledgeService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权操作");
            }
            if (parent.getIsFolder() == null || parent.getIsFolder() == 0) {
                return CommonResult.failed("请在文件夹下操作");
            }
        }
        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);
        Integer merId = userInfo.getMerId();
        Knowledge knowledge = knowledgeService.addKnowledge(request, userId, merId);
        Map<String, Object> data = new HashMap<>();
        data.put("result", knowledge != null ? 1 : 0);
        return CommonResult.success(data);
    }

    @ApiOperation(value = "获取知识库素材列表")
    @GetMapping("/listKnowledge")
    public CommonResult<List<Knowledge>> listKnowledge(@RequestParam(value = "parentId", required = false) Integer parentId, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        if (parentId != null && parentId != 0) {
            Knowledge parent = knowledgeService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权查看该文件夹");
            }
        }
        List<Knowledge> list = knowledgeService.listKnowledge(userId, parentId);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "根据ID获取知识库素材详情")
    @GetMapping("/getKnowledge")
    public CommonResult<Knowledge> getKnowledge(@RequestParam("id") Integer id, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        if (id == null) {
            return CommonResult.failed("知识库素材ID不能为空");
        }
        
        Knowledge knowledge = knowledgeService.getById(id);
        if (knowledge == null) {
            return CommonResult.failed("知识库素材不存在");
        }
        
        if (knowledge.getIsDel() == null || knowledge.getIsDel() != 0) {
            return CommonResult.failed("知识库素材已被删除");
        }
        
        if (!userId.equals(knowledge.getUserId())) {
            return CommonResult.failed("无权查看该知识库素材");
        }
        
        return CommonResult.success(knowledge);
    }

    @ApiOperation(value = "批量删除知识库素材（软删除）")
    @PostMapping("/delKnowledge")
    public CommonResult<Map<String, Object>> delKnowledge(@RequestBody BatchDeleteRequest request, HttpServletRequest httpRequest) {
        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return CommonResult.failed("请选择要删除的知识库素材");
        }
        
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        // 校验所有id对应的记录
        for (Integer id : ids) {
            Knowledge knowledge = knowledgeService.getById(id);
            if (knowledge == null || knowledge.getIsDel() == null || knowledge.getIsDel() != 0) {
                return CommonResult.failed("知识库素材ID " + id + " 不存在或已被删除");
            }
            if (!userId.equals(knowledge.getUserId())) {
                return CommonResult.failed("无权操作知识库素材ID " + id);
            }
        }
        
        boolean result = knowledgeService.batchDelKnowledge(ids);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result ? 1 : 0);
        return CommonResult.success(data);
    }
} 